/**
 * 新增主表信息弹出窗口
 * @param config
 * @returns
 */
function initWindow_report_config(config){
	return Ext.create('Ext.window.Window', {
        title: "报表配置", // 窗口标题
        width: document.body.clientWidth * 0.6, // 窗口宽度
        height: document.body.clientHeight * 0.7, // 窗口高度
        layout: 'fit',
        maximizable: true,
        name: 'window_report_config', // 窗口标识	
        buttonAlign: 'right', // 按钮显示的位置
        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
        closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是close，则会将window销毁。
        items: initWindow_report_config_contentForm(config),
        buttons: [{
        	text: '保存',
            name: 'save',
            handler: function (self) {
            	 self.setDisabled(true);
            	 var jbxxForm = Ext.ComponentQuery.query('form#jbxxForm'+config.xiugai)[0];
                 if (jbxxForm.isValid()) {
                 	var formData = jbxxForm.getForm().getFieldValues();
                    var qTable = formData.Q_TABLE;
                    if(qTable == null || qTable ==""){
                    	Ext.MessageBox.alert('提示', '请填写表/视图或数据源sql!');
                    	self.setDisabled(false);
                        return;
                    }
                    formData = $.extend({}, formData, jbxxForm.getValues());
                    formData.PARENT_ID = config.parent_id;
	                var url;
	                if(config.edit){
	                	url='/sys-report/updatejbxxInfo';
	                }else{
	                    url='/sys-report/savejbxxInfo';
	                }
	                $.post(url, {
	                	detailForm: Ext.util.JSON.encode([formData])
	                }, function (data) {
	                	if (data.success) {
	                    	Ext.toast({
	                        	html: "保存成功！",
	                            closable: false,
	                            align: 't',
	                            slideInDuration: 400,
	                            minWidth: 400
	                        });
	                        var parameter = "";
	                        if(!config.edit){
	                        	q_id = data.qid;
	                        }else{
	                        	parameter = data.condition
	                        }
	                        var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
                            rightConfig.removeAll(true);
	                        var table = Ext.ComponentQuery.query('textfield[name="Q_TABLE"]')[0].getValue();
	                        self.up('window').close();
	                        if(!config.edit){
	                        	if(table && table != null){
	    	    	            	Ext.Ajax.request({
	    	    	                	method : 'POST',
	    	    	                    url : "/sys-report/saveConditionInfoByTable",
	    	    	                    params : {
	    	    	                    	q_id: q_id,
	    	    	                        table:table
	    	    	                    },
	    	    	                    async : false,
	    	    	                    success : function(response, options) {
	    	    	                    	var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
	    	  	                            manageTreePanel.getStore().load({
		    	  	                        	callback: function(records, operation, success) {
		    	  	                            	var node = manageTreePanel.getStore().getNodeById(q_id);
		    	  	                              	currentReport = node;
		    	  	                              	manageTreePanel.getSelectionModel().select(node);
		    	  	                              	treeSearch(q_id);
		    	  	                              	changeReport(node);
		    	  	                             }
		    	  	                         });
	    	    	                    },
	    	    	                    failure : function(response, options) {
	    	    	                    	Ext.MessageBox.minWidth = 120;
	    	    	                        Ext.Msg.alert('提示', '获取表字段信息失败！');
	    	    	                    }
	    	    	            	});
	                        	}
	                        }else{
	                        	var manageTreePanel = Ext.ComponentQuery.query('treepanel#manageTree')[0];
	                        	manageTreePanel.getStore().load({
                          		    callback: function(records, operation, success) {
                          		    	var node = manageTreePanel.getStore().getNodeById(q_id);
                          		    	var table = node.get("table");
                          		    	var fieldTree = Ext.ComponentQuery.query('treepanel#fieldTree')[0];
                          		        var fieldStore = fieldTree.getStore();
                          		        fieldStore.getProxy().extraParams = {
                          		        	q_id:q_id
                          		        };
                          		        fieldStore.load();
                              		    for(var i = 0;i<parameter.length;i++){
				    						var flag = false;
				    						for(var j = conditionList.length;j>=0;j--){
				    							if(conditionList[j]){
				    								if(conditionList[j].C_CODE == parameter[i]){
				    				        			var flag = true;
				    				        		}
				    							}
				    						}
				    						if(!flag){
				    							changeFlag = true;
				    							var cid = GUID.createGUID();
 					    		        		conditionList.push({
 					    		        			C_ID:cid,
 					    		        			C_CODE:parameter[i],
 					    		            		C_TITLE: parameter[i],
 					    		            		IS_SHOW:0
 					    		        		});
				    				        }
			    				         }
                              		    var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
				    					conditionPanel.removeAll(true);
				    					conditionConf(conditionList);
                          		        
                          		        var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
                              			rightConfig.removeAll(true);
                              			var id = node.get('id');
                              			var text = node.get('text');
                              			var q_is_title = node.get('q_is_title');
                              			var unit = node.get('unit');
                              			var q_is_right = node.get('q_is_right');
                              			var q_is_page = node.get('q_is_page');
                              			var q_is_sum = node.get('q_is_sum');
                              			var q_is_openrun = node.get('q_is_openrun');
                              			var q_is_button = node.get('q_is_button');
                              			var q_remark = node.get('q_remark');
                              			var right_level = node.get('right_level');
                              			var export_level = node.get('export_level');
                              			var data = {
                              					Q_ID: id,
                              					Q_TITLE: text,
                              					Q_IS_TITLE: q_is_title,
                              					Q_TABLE: table,
                              					MONEY_UNIT: unit,
                              					Q_IS_RIGHT: q_is_right,
                              					Q_IS_PAGE: q_is_page,
                              					Q_IS_SUM: q_is_sum,
                              					Q_IS_OPENRUN: q_is_openrun,
                              					Q_REMARK:q_remark,
                              					Q_IS_BUTTON: q_is_button,
                              					RIGHT_LEVEL:right_level,
                              					EXPORT_LEVEL:export_level
                              				};
                              			//queryList = data;
                              			rightConfig.setTitle("基本信息配置");
                              			rightConfig.add(initWindow_report_config_contentForm({
                              				edit:true,
                              				columnWidth:.99,
                              			    data: data,
                              			    saveFlag:true
                              		    }));
//                          		    	changeReport(node);
                          		    }
	                        	});         
	                        }
	                	} else {
	                    	Ext.MessageBox.alert('提示', '保存失败!' + data.message);
	                    	self.setDisabled(false);
	                	}
	                }, 'JSON');
                 } 
            }
        },{
        	text: '关闭',
            handler: function (btn) {
                btn.up('window').close();
            }
                      
        }]
	}).show();
}


function initWindow_report_config_contentForm(config){
	//queryList saveFlag
	var columnWidth = .499;
	var tableColumnWidth = .75;
	var searchColumnWidth = .1;
	var searchMargin = '30 0 0 10';
	var editColumnWidth = .1;
	var editMargin = '30 0 0 10';
	if(config.columnWidth){
		columnWidth = config.columnWidth;
		tableColumnWidth = .99;
		editColumnWidth = .6;
		editMargin = '5 5 2 60';
		searchColumnWidth = .35;
		searchMargin = '5 5 2 10';
	}
	var xiugai="";
	if(config.xiugai){
		xiugai = config.xiugai;
	}
    var form = Ext.create('Ext.form.Panel', {
    	itemId: 'jbxxForm'+xiugai,
        width: '100%',
        height: '100%',
        layout: 'column',
        scrollable:true,
        defaults: {
        	 margin: '5 5 2 5',
             columnWidth: columnWidth,
             labelAlign: "right",
            //width: 315,
            labelWidth: 90//控件默认标签宽度
        },
        defaultType: 'textfield',
        items: [{
			fieldLabel: '<span class="required">✶</span>报表名',
			name: "Q_ID",
			allowBlank: false,
			editable: true,
			hidden:false,
			regex: /^[0-9a-zA-Z_]*$/,
			regexText : '只能输入数字字母下划线',
			maxLength:32
		},{
			fieldLabel: '<span class="required">✶</span>报表标题',
            name: "Q_TITLE",
            allowBlank: false,
            listeners:{
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag && config.saveFlag == "save"){
						var mainPanel = Ext.ComponentQuery.query('panel#condition')[0];
					    mainPanel.setTitle(newValue);
					    saveJbxxFormValues();
					}
				}
			}
       },{
       		xtype:"combobox",
            fieldLabel: '<span class="required">✶</span>显示标题',
            name: "Q_IS_TITLE",
            allowBlank: false,
	        store:  DebtEleStore(json_is_title),
	        queryMode: 'local',
	        editable: false,
	        allowBlank:false,
	        value : 1,
	        displayField: 'name',
	        valueField: 'id',
            listeners:{
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag && config.saveFlag == "save"){
						var mainPanel = Ext.ComponentQuery.query('panel#condition')[0];
					    saveJbxxFormValues();
					}
				}
			}
       },{ 
    	   xtype:'textareafield',
           fieldLabel: '<span class="required">✶</span>数据集',
           columnWidth: tableColumnWidth,
           name: "Q_TABLE",
           height:90,
           allowBlank: false,
           listeners:{
        	   change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag && config.saveFlag == "save"){
						saveJbxxFormValues();
					}
        	   }
           }
       },{
    	   xtype: 'button',
           text: '编辑',
           columnWidth:editColumnWidth,
           margin:editMargin,
           icon: '/report/image/sysbutton/edit.png',
           handler: function (self) {
           		var tableSql = "";
    	        var editSqlWindow = Ext.ComponentQuery.query('window[name="window_report_config"]')[0];
                if(editSqlWindow){
                	var windowForm = editSqlWindow.down('form#jbxxForm'+xiugai);
                    tableSql = windowForm.down('textareafield[name="Q_TABLE"]').getValue();
                }else{
                	tableSql = Ext.ComponentQuery.query('textfield[name="Q_TABLE"]')[0].getValue();
                }
                Ext.create('Ext.window.Window', {
                	title: '数据集修改', // 窗口标题
                    width: document.body.clientWidth * 0.7, // 窗口宽度
                    height: document.body.clientHeight * 0.7, // 窗口高度
                    layout: 'fit',
                    maximizable: true,
                    itemId: 'window_edit_table_sql', // 窗口标识
                    buttonAlign: 'right', // 按钮显示的位置
                    modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                    closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                    items: [{
                    	xtype: 'form',
	            		width: '100%',
	            		height: '100%',
	            		layout: 'column',
	            		autoScroll: true,
	            		defaults: {
	            			margin: '10 5 5 5',
	            			columnWidth:.99,
	            			labelAlign: "right",
	            			labelWidth: 100//控件默认标签宽度
	            		},
	            		items: [{
	            			xtype:'textareafield',
	            			height:'95%',
	            			name: 'EDIT_SQL',
	            			allowBlank: false,
	            			value:tableSql
	            		}]
                    }],
                    buttons: [{
                    	xtype: 'button',
                    	text: '确定',
                    	handler: function (self) {
                    		var editSql = Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[0].getValue();
                    	    var editSqlWindow = Ext.ComponentQuery.query('window[name="window_report_config"]')[0];
                            if(editSqlWindow){
                            	var windowForm = editSqlWindow.down('form#jbxxForm'+xiugai);
                                windowForm.down('textareafield[name="Q_TABLE"]').setValue(editSql);
                            }else{
                            	Ext.ComponentQuery.query('textareafield[name="Q_TABLE"]')[0].setValue(editSql);
                            }
                    	    self.up('window').close();
                    	}
                    },{
                    	xtype: 'button',
                    	text: '关闭',
                    	handler: function (self) {
                    		self.up('window').close();
                    	}
                    }]
                }).show();
           }
       },{
    	   xtype: 'button',
           text: '预览',
           columnWidth:searchColumnWidth,
           margin:searchMargin,
           icon: '/report/image/sysbutton/search.png',
           handler: function (self) {
        	   var window = Ext.ComponentQuery.query('window[name="window_report_config"]')[0];
               var table = "";
               var title = "";
               if(window){
               		var windowForm = window.down('form#jbxxForm'+xiugai);
                    table = windowForm.down('textareafield[name="Q_TABLE"]').getValue();
                    title = windowForm.down('textfield[name="Q_TITLE"]').getValue();
               }else{
               		table = Ext.ComponentQuery.query('textareafield[name="Q_TABLE"]')[0].getValue();
                    title = Ext.ComponentQuery.query('textfield[name="Q_TITLE"]')[0].getValue();
               }
                           
               if(table == null || table ==""){
               		Ext.MessageBox.alert('提示', '表/视图或数据源sql为空不可预览!');
                    return;
               }
               if(table.toUpperCase().indexOf("SELECT") == -1){
               		table = "select * from " + table;
               }
               table = encode64(table);
               $.post('/report/page/plat/sys/dataCheckExecute.action', {
               		RUNSQL:table
               }, function (data) {
            	   if (data.success&&data.select) {
                   		var parameter = data.condition;
                        if(parameter.length > 0){
                        	Ext.create('Ext.window.Window', {
                            	title:'参数',
                                width: document.body.clientWidth * 0.3, // 窗口宽度
                                height: document.body.clientHeight * 0.5, // 窗口高度
                                layout: 'fit',
                                maximizable: true,
                                itemId: 'window_table_condition_info', // 窗口标识
                                buttonAlign: 'right', // 按钮显示的位置
                                modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                                closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                                items: initWindow_table_condition_info(parameter),
                                buttons: [{
		                        	xtype: 'button',
		                            text: '确定',
		                            handler: function (self) {
		                            	var form = self.up('window').down('form');
		                                var formData = form.getValues();
		                                self.up('window').close();
	                                    $.post('/report/page/plat/sys/getTableDataHeader.action', {
	                                    	runsql:table
	                                    }, function (data) {
	                                    	if(data.header){
	                                        	//弹出弹出框
	                                    		Ext.create('Ext.window.Window', {
	                                            	title: title, // 窗口标题
	                                                width: document.body.clientWidth * 0.8, // 窗口宽度
	                                                height: document.body.clientHeight * 0.8, // 窗口高度
	                                                layout: 'fit',
	                                                maximizable: true,
	                                                itemId: 'window_table_info', // 窗口标识
	                                                buttonAlign: 'right', // 按钮显示的位置
	                                                modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
	                                                closeAction: 'destroy',
	                                                items: initWindow_table_info(table,data.header,title,formData),
	                                                buttons: [{
	                                                	xtype: 'button',
	                                                    text: '关闭',
	                                                    handler: function (self) {
	                                                    	self.up('window').close();
	                                                    }
	                                                }]
	                                    		}).show();
	                                    	}	
	                                    },'JSON');
		                            }
                                },{
		                        	xtype: 'button',
		                            text: '取消',
		                            handler: function (self) {
		                            	self.up('window').close();
		                            }
		                        }]
                        	}).show();
                        }else{
                        	$.post('/report/page/plat/sys/getTableDataHeader.action', {
                        		runsql:table
                            }, function (data) {
                            	if(data.header){
                            		//弹出弹出框
                                    Ext.create('Ext.window.Window', {
                                    	title: title, // 窗口标题
                                        width: document.body.clientWidth * 0.8, // 窗口宽度
                                        height: document.body.clientHeight * 0.8, // 窗口高度
                                        layout: 'fit',
                                        maximizable: true,
                                        itemId: 'window_table_info', // 窗口标识
                                        buttonAlign: 'right', // 按钮显示的位置
                                        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                                        closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                                        items: initWindow_table_info(table,data.header,title),
                                        buttons: [{
                                        	xtype: 'button',
                                         	text: '关闭',
                                         	handler: function (self) {
                                         		self.up('window').close();
                                         	}
                                        }]
                                    }).show();
                            	}	
                            },'JSON');
                        }
            	   } else if(data.success){
                   		Ext.MessageBox.alert('提示', '执行sql成功!');
                   }else{
                   		Ext.MessageBox.alert('提示', data.message);
                   }
               }, 'JSON');
           }
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>金额单位',
	       name:"MONEY_UNIT",
	       store:  DebtEleStore(json_unit),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 1,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	   
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>权限过滤',
	       name:"Q_IS_RIGHT",
	       store: DebtEleStore(json_right_type),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 0,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>数据分页',
	       name:"Q_IS_PAGE",
	       store: DebtEleStore(json_page),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 1,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>数据合计行',
	       name:"Q_IS_SUM",
	       store: DebtEleStore(json_sum),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 0,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>打开即查询',
	       name:"Q_IS_OPENRUN",
	       store: DebtEleStore(json_openrun),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 0,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	
       },{
    	   xtype:"combobox",
	       fieldLabel: '<span class="required">✶</span>常用按钮',
	       name:"Q_IS_BUTTON",
	       store: DebtEleStore(json_button),
	       queryMode: 'local',
	       editable: false,
	       allowBlank:false,
	       value : 1,
	       displayField: 'name',
	       valueField: 'id',
	       listeners:{
	    	   change : function( self, newValue, oldValue, eOpts ){
	    		   if(config.saveFlag && config.saveFlag == "save"){
	    			   saveJbxxFormValues();
	    		   }
	    	   }
	       }	
       },{
  		 xtype:"combobox",
		 fieldLabel: '<span class="required">✶</span>权限级次',
		 name:"RIGHT_LEVEL",
		 store: DebtEleStore(json_right_level),
		 queryMode: 'local',
		 editable: false,
		 allowBlank:false,
		 value : 0,
		 displayField: 'name',
		 valueField: 'id',
		 listeners:{
		    	change : function( self, newValue, oldValue, eOpts ){
		    		if(config.saveFlag && config.saveFlag == "save"){
		    			saveJbxxFormValues();
		    		}
		    	}
		    }	
	    },{
   		 xtype:"combobox",
		 fieldLabel: '<span class="required">✶</span>导出级次',
		 name:"EXPORT_LEVEL",
		 store: DebtEleStore(json_export_level),
		 queryMode: 'local',
		 editable: false,
		 allowBlank:false,
		 value : 1,
		 displayField: 'name',
		 valueField: 'id',
		 listeners:{
		    	change : function( self, newValue, oldValue, eOpts ){
		    		if(config.saveFlag && config.saveFlag == "save"){
		    			saveJbxxFormValues();
		    		}
		    	}
		    }	
	    },{
	       xtype:'textareafield',	
    	   fieldLabel: '报表说明',
           name: "Q_REMARK",
           columnWidth: tableColumnWidth,
           height:70,
           listeners:{
        	   change : function( self, newValue, oldValue, eOpts ){
        		   if(config.saveFlag && config.saveFlag == "save"){
        			   saveJbxxFormValues();
        		   }
        	   }
           }
       }]
    });
    if(config.edit){
    	form.down('textfield[name="Q_ID"]').setEditable(false);
    }
    form.getForm().setValues(config.data);
    queryList={};
    setTimeout(function () {  
    	if(config.saveFlag){
    		config.saveFlag="save";
    	}
    }, 1000); 
    return form;
}

function saveJbxxFormValues(){
	changeFlag = true;
	var form=Ext.ComponentQuery.query('form#jbxxForm')[0];
	var formValues = form.getForm().getValues();
	queryList = formValues;
}
